﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WP.Modules;
using WP.DB;
using WP.Controls;
using WP.Commons;
using System.Collections;
using WP.IM.DataAccess;

namespace WP.IM.Form
{
    public partial class frmImCategorySemiProductMtn : BaseMtn 
    {
        private DBAccess mdbcon = null;
        public frmImCategorySemiProductMtn()
        {
            InitializeComponent();
            mdbcon = new DBAccess(false, false);
            LoadAllControl(new ArrayList(this.Controls));
            this.MtnTabControl = this.tbcMain;
            this.DesignTabsName = "tbpGeneral";
            tbcMain.DrawMode = TabDrawMode.OwnerDrawFixed;
            this.MinimumSize = this.Size;
        }

        private void frmImSemiProductMtn_FormClosing(object sender, FormClosingEventArgs e)
        {
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgList);
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
           
            if (!this.UpdateData()) return;          
            base.SetStatusAfterUpdate();
        }
        private void btnNew_Click(object sender, EventArgs e)
        {
            if (this.ConfirmChange())
            {
                if (!this.UpdateData()) return;
            }
            this.formStatus = FormStatus.AddNew;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!this.DeleteData()) return;
            //this.tvTree.SelectedNode.Remove();
            FillCategtory(); 
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.formStatus = FormStatus.Delete;
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
            {
                if (this.ConfirmChange())
                {
                    if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (!this.UpdateData()) return;
                    }
                }
            }
            this.ExitingStatus = true;
            this.Close();
        }

        public override void InitDeftValue()
        {
            base.InitDeftValue();
            if (this.formStatus == FormStatus.AddNew)
            {
                string strCategoryID = GetCategoryFromTree(this.tvTree.SelectedNode);
                txtCategoryID.Text = strCategoryID;
                txtCategoryName.Text = CvtFunc.ToString ( mdbcon.GetValue ( "select categoryname from rmCategory where CategoryID='"+ strCategoryID +"'"));

                if (this.tvTree.SelectedNode.Level >= 1)
                {
                    this.txtParentSemiID.Text = CvtFunc.ToString(this.tvTree.SelectedNode.Tag);
                    this.txtParentSemiCode.Text = CvtFunc.ToString(mdbcon.GetValue("select SemiCode from imCategorySemiProduct where RecID='" + this.txtParentSemiID.Text + "'"));
                    this.txtParentSemiName.Text = CvtFunc.ToString(mdbcon.GetValue("select SemiName from imCategorySemiProduct where RecID='" + this.txtParentSemiID.Text + "'"));   
                }
            }
        }

        private string GetCategoryFromTree(TreeNode trNode)
        {
            if (trNode == null) return "";
            TreeNode tNode = trNode ;
            while (tNode.Parent != null)
            {
                tNode = tNode.Parent;
            }
            return CvtFunc.ToString(tNode.Tag);
        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            base.OnHelp();
        }
        private void btnToExcel_Click(object sender, EventArgs e)
        {
            base.ExportToExcel(dgList);
        }
        private void btnNext_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Next);
        }
        private void btnPrev_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Prev);
        }
        private void btnTop_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Top);
        }
        private void btnBottom_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Bottom);
        }
        public override void SetNavigatorBarTooltip()
        {
            if (this.RecID <= 0)
            {
                this.btnBottom.ToolTipText = "定位到末页";
                this.btnTop.ToolTipText = "定位到首页";
                this.btnNext.ToolTipText = "定位到下一页";
                this.btnPrev.ToolTipText = "定位到前一页";
            }
            else
            {
                this.btnBottom.ToolTipText = "定位到末记录";
                this.btnTop.ToolTipText = "定位到首记录";
                this.btnNext.ToolTipText = "定位到下一条记录";
                this.btnPrev.ToolTipText = "定位到上一条记录";
            }
        }

        private void dgList_DefineColumn(object sender, EventArgs e)
        {
            base.SelectListViewField(dgList);
        }
        private void dgList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && dgList.CurrentRow != null)
            {
                this.RecID = Convert.ToInt64(dgList.RecID);
            }
        }
        private void dgList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (dgList.CurrentRow != null && BaseFunctions.IsDataGridCell(this.dgList, e))
            {
                this.RecID = Convert.ToInt64(dgList.RecID);
            }
        }

        protected override void Field_Leave(object sender, System.EventArgs e)
        {
            base.Field_Leave(sender, e);
            Control con = sender as Control;
            if (con == null) return;

            //below is some speci field , need do some speci work

        }
        protected override void Field_Change(object sender, EventArgs e)
        {
            base.Field_Change(sender, e);
            if (this.formStatus == FormStatus.Delete) return;
            Control con = sender as Control;
            if (con == null) return;
            if (con.Name == this.txtParentSemiID.Name)
            {
                this.txtParentSemiName.Text = CvtFunc.ToString(mdbcon.GetValue("select SemiName from imSemiProduct where SemiCode='" + this.txtParentSemiCode.Text + "'"));   
            }
            else
            {

            }
        }
        protected override void Field_KeyPress(object sender, KeyPressEventArgs e)
        {
            base.Field_KeyPress(sender, e);
        }

        private void tbcMain_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if ((this.formStatus == FormStatus.Query || this.formStatus == FormStatus.Delete) &&
                this.dgList.Rows.Count == 0 && e.TabPageIndex > 0)
            {
                e.Cancel = true;
                return;
            }

            if (e.TabPageIndex == 0)
            {
                if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
                {
                    if (this.ConfirmChange())
                    {
                        if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            if (!this.UpdateData())
                            {
                                if (m_bTabPageNeedCancel)
                                    e.Cancel = true;

                                m_bTabPageNeedCancel = true;
                                return;
                            }
                        }
                    }
                    this.formStatus = FormStatus.Delete;
                }
                else if (this.formStatus == FormStatus.Query)
                {
                    this.formStatus = FormStatus.Delete;
                }
                this.dgList.RefreshData();
                this.dgList.Focus();
            }
            else if (e.TabPageIndex != 0 && this.formStatus != FormStatus.AddNew)
            {
                if (this.RecID == -1)
                    this.RecID = Convert.ToInt64(dgList.RecID);


            }
        }
        private void tbcMain_DrawItem(object sender, DrawItemEventArgs e)
        {
            BaseFunctions.TabControl_DrawItem(sender, e, true);
        }
        private void FileMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mnuItem = sender as ToolStripMenuItem;
            if (mnuItem != null)
            {
                switch (mnuItem.Name)
                {
                    case "newToolStripMenuItem":
                        btnNew_Click(sender, e);
                        break;
                    case "cancelToolStripMenuItem":
                        btnCancel_Click(sender, e);
                        break;
                    case "deleteToolStripMenuItem":
                        btnDelete_Click(sender, e);
                        break;
                    case "saveToolStripMenuItem":
                        btnUpdate_Click(sender, e);
                        break;
                    case "exitToolStripMenuItem":
                        btnExit_Click(sender, e);
                        break;
                }
            }
        }

        #region ***Form Functions

        private TreeNode GetParentNode(TreeNode trNode)
        {
            foreach (TreeNode tvNode in trNode.Nodes)
            {
                if (CvtFunc.ToString(tvNode.Tag) == txtParentSemiID.Text)
                {
                    return tvNode;
                }
                else if (tvNode.Nodes.Count > 0)
                {
                    TreeNode trtmp = GetParentNode(tvNode);
                    if (trtmp != null) return trtmp;
                }
            }
            return null;
        }

        public override bool UpdateData()
        {
            bool bUpdateResult = true;
            FormStatus frmOldStatus = new FormStatus();
            frmOldStatus = this.formStatus;
            if (base.ConfirmChange())
            {
                bool blnParent = this.ControlValueChanged(txtParentSemiCode); 
                bUpdateResult = base.UpdateData();
               
                TreeNode trNode = new TreeNode();
                trNode.Text = txtSemiCode.Text + "-" + txtSemiName.Text;
                trNode.Tag = this.m_lRecId;
                if (frmOldStatus == FormStatus.AddNew)
                {
                    if (txtParentSemiID.Text == this.tvTree.SelectedNode.Tag)
                    {
                        this.tvTree.SelectedNode.Nodes.Add(trNode);
                    }
                    else
                    {
                        foreach (TreeNode tvNode in this.tvTree.Nodes)
                        {
                            TreeNode tvParent = GetParentNode(tvNode);
                            if (tvParent != null)
                            {
                                tvParent.Nodes.Add(trNode);  
                            }
                        }
                    }
                }
                else
                {
                    if (blnParent)
                    {
                        this.tvTree.Nodes.Clear();
                        FillCategtory();
                    }
                    else
                    {
                        this.tvTree.SelectedNode.Text = trNode.Text;
                        trNode.Tag = this.m_lRecId;
                    }
                }
            }
            return bUpdateResult;
        }
        public override bool ConfirmChange()
        {
            return (base.ConfirmChange());
        }
        protected override bool FieldCheck(string strFieldValue, string strFieldName, ref string strErrPrompt)
        {

            strErrPrompt = string.Empty;
            DBAccess dBAccess = new DBAccess(false, false);
            DataRow dr = base.GetCurrentMtnDataRow();


            IM.BusinessRule.ImSemiProductBRL mBRL = new WP.IM.BusinessRule.ImSemiProductBRL();
            bool bCheckResult = mBRL.FieldCheck(dBAccess, dr, strFieldName, ref strErrPrompt, this.formStatus);
            dBAccess.CloseCon();
            return bCheckResult;

        }
        protected override string GetLookUpSQL(string strTableName, string strLookUpControlName)
        {
            string strSql = string.Empty;
            if (strLookUpControlName == ubtParentSemiID.Name)
            {
                DataFunctions.DelTemporyTable(mdbcon, "#tmpRecID"); 
                string  strTmpSql =@"  with cte as
                            (
                                select RECID, SemiCode,SemiName,ParentSemiID,0 as lvl from imCategorySemiProduct
                                where recId = {0}
                                union all
                                select D.RECID,d.SemiCode,d.SemiName,D.ParentSemiID,lvl+1 from cte c inner join imCategorySemiProduct d
                                on c.recId = d.ParentSemiID
                            )
                            select * into #tmpRecID from cte where lvl>0";
                strTmpSql = string.Format(strTmpSql, this.m_lRecId);
                mdbcon.ExecuteSql(strTmpSql);


                strSql = "select * from imCategorySemiProduct where CategoryID='" + txtCategoryID.Text + "' and RecID!='" + this.RecID + "'";
                strSql += " and SemiCode not in (select SemiCode from #tmpRecID )";
                return strSql;
            }
            else if ( strLookUpControlName == ubtSemiCode.Name)
            {
                strSql = "select * from imSemiProduct where SemiCode!='" + this.txtSemiCode.Text  + "'";
                strSql += " and SemiCode not in (select SemiCode from imCategorySemiProduct where CategoryID='" + txtCategoryID.Text + "')";
                return strSql;
            }
            else 
                return base.GetLookUpSQL(strTableName, strLookUpControlName);
        }

        protected override void ubtLookUp_Click(object sender, EventArgs e)
        {
            Control con = sender as Control;
            if (con.Name == ubtParentSemiID.Name)
            {
                string strSQL = GetLookUpSQL( "imCategorySemiProduct",ubtParentSemiID.Name );

                frmLookUp frmup = new frmLookUp(mdbcon, strSQL, "", "", "RecID");
                frmup.ShowDialog();
                if (frmup.HaveReturnValue)
                {
                    txtParentSemiID.Text = frmup.GetReturnValue("RecID");
                    txtParentSemiCode.Text = frmup.GetReturnValue("SemiCode");
                    txtParentSemiName.Text = frmup.GetReturnValue("SemiName");  
                }
            }
            else
            {
                base.ubtLookUp_Click(sender, e);
            }
        }

        
        public override void SetButtonStatus()
        {
            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = false;
                    this.btnCancel.Enabled = true;
                    this.utrconfirmed.Enabled = false;
                    this.udtconfirmDate.Enabled = false;
                    this.txtconfirmBy.Enabled = false;
                    this.btnApproHistory.Enabled = true;
                    break;
                case FormStatus.Delete:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = (true && this.CurrentMenuInfo.strPermit == "Y");
                    this.btnCancel.Enabled = false;
                    this.utrconfirmed.Enabled = false;
                    this.udtconfirmDate.Enabled = false;
                    this.txtconfirmBy.Enabled = false;
                    this.btnApproHistory.Enabled = true;
                    break;
                case FormStatus.Query:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = (true && this.CurrentMenuInfo.strPermit == "Y");
                    this.btnCancel.Enabled = false;
                    this.utrconfirmed.Enabled = false;
                    this.udtconfirmDate.Enabled = false;
                    this.txtconfirmBy.Enabled = false;
                    this.btnApproHistory.Enabled = true  ;
                    break;
                case FormStatus.Update:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = true;
                    this.btnNew.Enabled = true;
                    this.btnCancel.Enabled = true;
                    this.utrconfirmed.Enabled = true;
                    this.udtconfirmDate.Enabled = true;
                    this.txtconfirmBy.Enabled = true;
                    this.btnApproHistory.Enabled = true;
                    
                    break;
                case FormStatus.Loading:
                    break;

            }

            this.btnToExcel.Visible = (this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query) && SysVar.AbleToExcel;
            this.btnToExcel.Enabled = this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query;

            newToolStripMenuItem.Enabled = btnNew.Enabled;
            cancelToolStripMenuItem.Enabled = btnCancel.Enabled;
            deleteToolStripMenuItem.Enabled = btnDelete.Enabled;
            saveToolStripMenuItem.Enabled = btnUpdate.Enabled;

            if (utrconfirmed.Text == "Yes")
            {
                BaseFunctions.ControlEnabled(this.toolStrip, false);
                this.btnUnConfirm.Enabled = true;
                this.btnConfirm.Enabled = false;
            }
            else
            {
                this.btnConfirm.Enabled = true;
                this.btnUnConfirm.Enabled = false;
            }

            if ( this.tvTree.SelectedNode !=null && this.tvTree.SelectedNode.Parent  == null)
            {
                string strCategory = this.tvTree.SelectedNode.Text.Substring(0, 3);
                if (CvtFunc.ToDouble(mdbcon.GetValue("select count(*) from imCategorySemiProduct where confirmed=1 and CategoryID='" + strCategory + "'")) > 0)
                {
                    this.btnUnConfirm.Enabled = true;
                    this.btnConfirm.Enabled = false;
                }
                else
                {
                    this.btnUnConfirm.Enabled = false;
                    this.btnConfirm.Enabled = true;
                }
            }

            this.btnTop.Enabled = true;
            this.btnBottom.Enabled = true;
            this.btnPrev.Enabled = true;
            this.btnNext.Enabled = true;
            this.btnHelp.Enabled = true;
            this.btnExit.Enabled = true;

           
        }

        public override void SetControlEditStatus()
        {
            base.SetControlEditStatus();
            if (CvtFunc.ToBoolean(utrconfirmed.Text))
            {
                gpbDetail.Enabled = false;
            }
            else
            {
                gpbDetail.Enabled = true ;
            }
        }
        public override void SetOtherStatus()
        {

            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    this.txtSemiCode.Focus();
                    break;
                case FormStatus.Delete:
                    break;
                case FormStatus.Query:
                    break;
                case FormStatus.Update:
                    break;
                case FormStatus.Loading:
                    break;
            }


        }
        public override void RefreshOverView()
        {
            base.RefreshOverView();
            if (this.RecID != -1)
                this.dgList.RecID = this.RecID;
        }

        private void FillLookUpInfo()
        {
            SetFieldLookUpInfo("CategoryID", "rmCategory", "CategoryID", "ubtCategoryID");
            SetFieldLookUpInfo("CategoryName", "rmCategory", "CategoryName", "ubtCategoryID");

            SetFieldLookUpInfo("ParentSemiID", "imSemiProduct", "RecID", "ubtParentSemiID");
            SetFieldLookUpInfo("ParentSemiCode", "imSemiProduct", "SemiCode", "ubtParentSemiID");

            SetFieldLookUpInfo("SemiCode", "imSemiProduct", "SemiCode", "ubtSemiCode");
            SetFieldLookUpInfo("SemiName", "imSemiProduct", "SemiName", "ubtSemiCode");

            SetFieldLookUpInfo("Unit", "imUnit","Unit", "ubtUnit");
        }

        #endregion Form Functions***

        private void frmImSemiProductMtn_Load(object sender, EventArgs e)
        {
            this.TableName = "imCategorySemiProduct";
            dgList.ConnectionString = DBAccess.ConnectionDBString;
            dgList.TableName = this.TableName;
            dgList.ColumnWidth = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgList.Name);
            string strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            dgList.Sql = strSql;
            this.formStatus = FormStatus.Query;

            FillLookUpInfo();
            FillCategtory();
        }

        private string GetCategoryID(TreeNode trNode)
        {
            string strCategory = "";
            if (this.tvTree.SelectedNode != null && this.tvTree.SelectedNode.Parent == null)
            {
                strCategory = trNode.Text.Substring(0, 3);
            }
            else
            {
                while (trNode.Parent != null)
                {
                    trNode = trNode.Parent ;
                    GetCategoryID(trNode);
                }
            }
            return strCategory;
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            string strCategory = GetCategoryID(this.tvTree.SelectedNode);
            ImCategorySemiProductDAL imDAL = new ImCategorySemiProductDAL();
            imDAL.Confirm(strCategory);
            this.SetStatusAfterUpdate(); 
        }

        private void btnUnConfirm_Click(object sender, EventArgs e)
        {
            ImCategorySemiProductDAL imDAL = new ImCategorySemiProductDAL();
            string strCateID = GetCategoryFromTree(this.tvTree.SelectedNode);
            imDAL.unConfirm(strCateID);
            this.SetStatusAfterUpdate();
        }


        #region FillTree
        private void FillCategtory()
        {
            this.tvTree.Nodes.Clear();  
            string strSQL = "select * from rmCategory Order By CategoryID";
            DataTable dtCategory = mdbcon.GetDataTable(strSQL);
            foreach (DataRow drCategory in dtCategory.Rows)
            {
                TreeNode tvNode = new TreeNode(CvtFunc.ToString(drCategory["CategoryID"]) + "-" + CvtFunc.ToString(drCategory["CategoryName"]));
                tvNode.Tag = CvtFunc.ToString(drCategory["CategoryID"]);
                this.tvTree.Nodes.Add(tvNode);
                FillSemiHdr(tvNode);
            }
        }

        private void FillSemiHdr(TreeNode tvNode)
        {
            string strSQL = "select * from imCategorySemiProduct where ParentSemiID= 0 and CategoryID='" + tvNode.Tag + "'  order by SemiCode";
            DataTable dtSemiHdr = mdbcon.GetDataTable(strSQL);
            foreach (DataRow drSemiHdr in dtSemiHdr.Rows)
            {
                TreeNode tvNodeHdr = new TreeNode(CvtFunc.ToString(drSemiHdr["SemiCode"]) + "-" + CvtFunc.ToString(drSemiHdr["SemiName"]));
                tvNodeHdr.Tag = CvtFunc.ToString(drSemiHdr["RecID"]);
                tvNode.Nodes.Add(tvNodeHdr);
                string strRecID = CvtFunc.ToString(tvNodeHdr.Tag);
                strSQL = @"with cte as
                            (
                                select RECID, SemiCode,SemiName,ParentSemiID,0 as lvl from imCategorySemiProduct
                                where recId = {0}
                                union all
                                select D.RECID,d.SemiCode,d.SemiName,D.ParentSemiID,lvl+1 from cte c inner join imCategorySemiProduct d
                                on c.recId = d.ParentSemiID
                            )
                            select * from cte where lvl>0";
                strSQL = string.Format(strSQL, strRecID);
                DataView dvSemi = mdbcon.GetDataTable(strSQL).DefaultView;
                FillSemiProduct(tvNodeHdr, dvSemi);
            }
        }

        private void FillSemiProduct(TreeNode tvNode, DataView dvSemi)
        {

            dvSemi.RowFilter = " ParentSemiID ='" + CvtFunc.ToString(tvNode.Tag) + "'";
            if (dvSemi.Count > 0)
            {
                foreach (DataRowView dgv in dvSemi)
                {
                    TreeNode tvNodeHdr = new TreeNode(CvtFunc.ToString(dgv["SemiCode"]) + "-" + CvtFunc.ToString(dgv["SemiName"]));
                    tvNodeHdr.Tag = CvtFunc.ToString(dgv["RecID"]);
                    tvNode.Nodes.Add(tvNodeHdr);
                    FillSemiProduct(tvNodeHdr, dvSemi); 
                }
            }
        }


        #endregion

        private void tvTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                if (this.tbcMain.SelectedTab == tbpGeneral)
                {
                    this.tbcMain.SelectedTab = tbpOverview;
                }

                if (BaseFunctions.IsNumeric( CvtFunc.ToString ( e.Node.Tag)) && e.Node.Text.Substring(0,1)=="B")
                {
                    dgList.RecID = CvtFunc.ToLong(e.Node.Tag);
                    this.RecID = Convert.ToInt64(dgList.RecID);
                }
                else
                {
                    dgList.RecID = -1;
                    this.RecID =-1;
                }
            }
        }

        private void btnApproHistory_Click(object sender, EventArgs e)
        {
            string strCate = GetCategoryFromTree(this.tvTree.SelectedNode);  
            frmApprovalHistory frmHist = new frmApprovalHistory(mdbcon, frmApprovalHistory.TableType.CagtegorySemi, strCate);
            frmHist.Text = "审核历史记录";
            frmHist.ShowDialog(); 
        }
    }
}
